package main

import (
	"encoding/json"
	"fmt"
	"net"
	"strconv"
	"strings"
	"time"
)

func main() {
	listener, err := net.Listen("tcp", "0.0.0.0:21231") //侦听端口21231
	if err != nil {
		fmt.Println("listen error:", err)
		return
	}
	fmt.Println("server start..., listen: ", 21231)

	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("accept error:", err)
			break
		}

		go process(conn) //goroutine
	}
}

func process(conn net.Conn) {

	defer conn.Close()

	//读取req json长度
	buf := make([]byte, 12) //长度行总是12字节
	n, _ := conn.Read(buf)
	bufStr := string(buf[:n])
	// print("lenStr: ", lenStr)
	lenStr := strings.Trim(bufStr, "\r\n") //去除行尾的回车换行
	lenStr = strings.Trim(lenStr, " ")     //去除行左的空格
	len, _ := strconv.Atoi(lenStr)         //string转int

	//读取req json
	jsonBuf := make([]byte, len)
	n, _ = conn.Read(jsonBuf)
	// println("|", bufStr, string(jsonBuf[:n]), "|")

	//解析req json
	m := make(map[string]interface{}) //map
	json.Unmarshal(jsonBuf, &m)       //json转map
	method := m["head"].(map[string]interface{})["method"]
	data := m["data"]
	// fmt.Println("method: ", method)
	// fmt.Println("data: ", data)

	//调用业务函数
	var rspJson []byte
	var rsplen int
	switch method {
	case "aaa.BBB::hello":
		rspJson, rsplen = hello(data.(map[string]interface{}))
	default:
		rspJson, rsplen = foo()
	}

	//返回 rsp json
	lenRsp := fmt.Sprintf("%10d\r\n", rsplen)
	conn.Write([]byte(lenRsp)) //socket返回 长度行
	conn.Write(rspJson)        //socket返回 rsp json
}

func hello(m map[string]interface{}) ([]byte, int) {
	m["time"] = time.Now().Format("2006-01-02 15:04:05")
	m["module"] = "golang"
	b, _ := json.Marshal(m) //map转json
	return b, len(b)
}

func foo() ([]byte, int) {
	b := []byte("{}")
	return b, len(b)
}
